package com.laicunba.ext.web.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.laicunba.ext.web.annotation.ResponseCache;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.SessionUtil;
import com.laicunba.util.StringUtil; 

@Component
public class CacheFilter implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		SessionUtil.RESPONSE_CACHE_KEY.remove();
		ResponseCache cache = handler.getClass().getAnnotation(ResponseCache.class);
		if (cache == null) {
			return true;
		}
		String key = request.getRequestURI();
		if (StringUtil.isNotEmpty(cache.key())) {
			key = cache.key();
		} else if (StringUtil.isNotEmpty(cache.keyparam())) {
			key += "?";
			for (String pName : cache.keyparam().split(",")) {
				key += "&" + pName + "=" + request.getParameter(pName);
			}
		}
		if (StringUtil.isNotEmpty(SessionUtil.CURRENT_USER_ID.get())) {
			key = "uid:" + SessionUtil.CURRENT_USER_ID.get() + ":" + key;
		}

		key = "resp." + key;
		String responseTxt = CacheUtil.getAttribute(key);
		if (StringUtil.isEmpty(responseTxt)) {
			SessionUtil.RESPONSE_CACHE_KEY.set(key);
			SessionUtil.RESPONSE_CACHE_TIME.set(cache.time());
			return true;
		}
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(responseTxt);
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
